package utils

import (
	"errors"
	"time"

	"github.com/golang-jwt/jwt/v5"
)

type JwtUser struct {
	Id       int
	Username string
	DeptId   int
	DeptTier string
	IsAdmin  int
	RoleId   int
}

type JwtClaims struct {
	JwtUser
	jwt.RegisteredClaims
}

func GetJwtToken(secretKey string, user JwtUser) (string, error) {
	claims := JwtClaims{
		JwtUser: user,
		RegisteredClaims: jwt.RegisteredClaims{
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour * 24 * 7)),
			IssuedAt:  jwt.NewNumericDate(time.Now()),
			NotBefore: jwt.NewNumericDate(time.Now()),
		},
	}
	return jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString([]byte(secretKey))
}

func ParseTokenHs256(token_string string, sign_key string) (JwtUser, error) {
	token, err := jwt.ParseWithClaims(token_string, &JwtClaims{}, func(token *jwt.Token) (interface{}, error) {
		return []byte(sign_key), nil //返回签名密钥
	})
	if err != nil {
		return JwtUser{}, err
	}
	if claims, ok := token.Claims.(*JwtClaims); ok && token.Valid {
		return claims.JwtUser, nil
	} else {
		return JwtUser{}, errors.New("token invalid")
	}
}
